
using System;
using Habazie.kf2.Core;

namespace Habazie.kf2.Exposition
{
	
	/// <summary>
	/// 	A TextBuffewr with a few extras
	/// </summary>
	public class UltraTextBuffer : Gtk.TextBuffer
	{
		/// <summary>
		/// 	User has started typing
		/// </summary>
		public event EventHandler ComposingStart;
		
		
		/// <summary>
		/// 	User has stopped typing
		/// </summary>
		public event EventHandler ComposingStop;
		
		
		/// <summary>
		/// 	User is typing
		/// </summary>
		private bool m_Typing = false;
		
		private uint m_StateId = 0;
		
		private uint m_IdleTime = 5000;
		
		
		/// <summary>
		/// 	Public constructor
		/// </summary>
		public UltraTextBuffer() : base (null)
		{
			ComposingStart += OnComposingStart;
			ComposingStop += OnComposingStop;
		}
		
		
		/// <summary>
		/// 	Amount of time after which ComposingStop is triggered 	
		/// </summary>
		public uint IdleTime {
			get { return m_IdleTime; }
			set { m_IdleTime = value; }
		}
		
		
		/// <summary>
		/// 	Buffer was changed
		/// </summary>
		protected override void OnChanged ()
		{
			if (! m_Typing) {
				m_Typing = true;
				ComposingStart (this, new EventArgs ());
			}
			
			if (m_Typing) {
				if (m_StateId != 0) {
					GLib.Source.Remove (m_StateId);
					m_StateId = 0;
				} else {
					m_StateId = GLib.Timeout.Add (m_IdleTime, delegate {
						/* User has been idle for 5 seconds */
						if (m_Typing) {
							m_Typing = false;
							ComposingStop (this, new EventArgs ());
						}
						m_StateId = 0;
						return false;
					});
				}
			}
		}
		
		
		/// <summary>
		/// 	Default handler for ComposingStart event.
		/// </summary>
		protected virtual void OnComposingStart (object o, EventArgs args)
		{
//			Util.Debug ("Exposition", "ComposingStart");
		}
		
		
		/// <summary>
		/// 	Default handler for ComposingStop event.
		/// </summary>
		protected virtual void OnComposingStop (object o, EventArgs args)
		{
//			Util.Debug ("Exposition", "ComposingStop");
		}
	}
}
